package com.sunchangming.uniqname;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import com.google.protobuf.Descriptors.MethodDescriptor;

public class ServerIoHandler extends IoHandlerAdapter {
	private static volatile boolean inited = false;
	private final java.util.concurrent.ConcurrentHashMap<IoSession, Session> sessions = new java.util.concurrent.ConcurrentHashMap<IoSession, Session>();

	ServerIoHandler() {
		if (inited)
			throw new RuntimeException("为什么？？我只能有一个");

		inited = true;
	}

	@Override
	public void sessionClosed(IoSession session) throws Exception {
		sessions.remove(session);
		super.sessionClosed(session);
	}

	public int getConnectCount() {
		return sessions.size();
	}

	@Override
	public void sessionOpened(IoSession session) throws Exception {
		sessions.put(session, new Session(session));
	}

	@Override
	public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
		// TODO Auto-generated method stub
		super.sessionIdle(session, status);
	}

	@Override
	public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
		session.close(false);
	}

	@Override
	public void messageReceived(IoSession session, Object message) throws Exception {
		// 现在在哪个线程？
		Res req = (Res) message;
		MethodDescriptor md = ServerMain.getBlockingService().getDescriptorForType().getMethods().get(req.methodid);
		com.google.protobuf.Message res = ServerMain.getBlockingService().callBlockingMethod(md,
				new MyRpcController(sessions.get(session)), req.msg);
		session.write(new Res(res, md.getIndex()));
	}

}
